/**
 * @file XListView.java
 * @package me.maxwin.view
 * @create Mar 18, 2012 6:28:41 PM
 * @author Maxwin
 * @description An ListView support (a) Pull down to refresh, (b) Pull up to load more.
 * Implement IXListViewListener, and see stopRefresh() / stopLoadMore().
 */
package com.everflourish.yeah100.ui;

import android.content.Context;
import android.os.AsyncTask;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.view.animation.DecelerateInterpolator;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Scroller;
import android.widget.TextView;

import com.everflourish.yeah100.R;

public class XListView extends ListView implements OnScrollListener {

    // 滚动listview后，需要隐藏的控件
    private View mRollHiddenView;

    private float mLastY = -1; // save event y

    private Scroller mScroller; // used for scroll back

    private OnScrollListener mScrollListener; // user's scroll listener

    // the interface to trigger refresh and load more.
    private IXListViewListener mListViewListener;

    // -- header view
    private XListViewHeader mHeaderView;

    /** 头部的内容 */
    private RelativeLayout mHeaderViewContent;
    /** 头部的时间 */
    private TextView mHeaderTimeView;
    private LinearLayout mHeaderTimeTextView;

    private int mHeaderViewHeight; // header view's height

    private boolean mEnablePullRefresh = false; // 是否下拉加载加载更多

    private boolean mPullRefreshing = false; // 是否正在刷新

    // -- footer view
    private XListViewFooter mFooterView;

    private boolean mEnablePullLoad = false; // 是否滑动到底部加载更多

    private boolean mPullLoading; // 是否正在加载更多

    private boolean mIsFooterReady = false;

    // total list items, used to detect is at the bottom of listview.
    private int mTotalItemCount;

    // for mScroller, scroll back from header or footer.
    private int mScrollBack;

    private boolean mRollBottonIsMoveHiddenView = false;

    /** 滚动到页眉 */
    private final static int SCROLLBACK_HEADER = 0;
    /** 滚动到页脚 */
    private final static int SCROLLBACK_FOOTER = 1;
    /** 拉动持续时间 */
    private final static int SCROLL_DURATION = 400; // scroll back duration
    /** 拉动的像素大于多少触发 */
    private final static int PULL_LOAD_MORE_DELTA = 50; // when pull up >= 50px
    // at bottom, trigger
    // load more.

    private final static float OFFSET_RADIO = 1.8f; // support iOS like pull
    // feature.
    private boolean isPullMore = true;

    public boolean isPullMore() {
        return isPullMore;
    }

    public void setPullMore(boolean isPullMore) {
        this.isPullMore = isPullMore;
    }

    /**
     * @param context
     */
    public XListView(Context context) {
        super(context);
        initWithContext(context);
    }

    public XListView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initWithContext(context);
    }

    public XListView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        initWithContext(context);
    }

    private void initWithContext(Context context) {
        mScroller = new Scroller(context, new DecelerateInterpolator());
        // XListView need the scroll event, and it will dispatch the event to
        // user's listener (as a proxy).
        super.setOnScrollListener(this);

        // init header view
        mHeaderView = new XListViewHeader(context);
        mFooterView = new XListViewFooter(context);
        mHeaderViewContent = (RelativeLayout) mHeaderView
                .findViewById(R.id.xlistview_header_content);
        mHeaderTimeTextView = (LinearLayout) mHeaderView
                .findViewById(R.id.xlistview_header_time_ll);
        mHeaderTimeView = (TextView) mHeaderView
                .findViewById(R.id.xlistview_header_time);
        mHeaderTimeTextView.setVisibility(View.GONE);
        addHeaderView(mHeaderView);
        if (!mEnablePullRefresh) { // disable, hide the content
            mHeaderViewContent.setVisibility(View.INVISIBLE);
        } else {
            mHeaderViewContent.setVisibility(View.VISIBLE);
        }
        // init footer view

        // init header height
        mHeaderView.getViewTreeObserver().addOnGlobalLayoutListener(
                new OnGlobalLayoutListener() {
                    @Override
                    public void onGlobalLayout() {
                        mHeaderViewHeight = mHeaderViewContent.getHeight();
                        getViewTreeObserver()
                                .removeGlobalOnLayoutListener(this);
                    }
                });
    }

    @Override
    public void setAdapter(ListAdapter adapter) {
        // make sure XListViewFooter is the last footer view, and only add once.
        if (mIsFooterReady == false) {
            mIsFooterReady = true;
            // addFooterView(mFooterView);
        }
        super.setAdapter(adapter);
    }

    /**
     * enable or disable pull down refresh feature.
     *
     * @param enable
     */
    public void setPullRefreshEnable(boolean enable) {
        mEnablePullRefresh = enable;
        if (!mEnablePullRefresh) { // disable, hide the content
            mHeaderViewContent.setVisibility(View.INVISIBLE);
        } else {
            mHeaderViewContent.setVisibility(View.VISIBLE);
        }
    }

    /**
     * enable or disable pull up load more feature.
     *
     * @param enable
     */
    public void setPullLoadEnable(boolean enable) {
        mEnablePullLoad = enable;
        if (!mEnablePullLoad) {
            // boolean removeFooterView = removeFooterView(mFooterView);
            // System.out.println(removeFooterView);
            mFooterView.hide();
            mFooterView.setOnClickListener(null);
        } else {
            removeFooterView(mFooterView);
            addFooterView(mFooterView);
            mPullLoading = false;
            mFooterView.show();
            mFooterView.setState(XListViewFooter.STATE_NORMAL);
            // both "pull up" and "click" will invoke load more.
            mFooterView.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    startLoadMore();
                }
            });
        }
    }

    /**
     * stop refresh, reset header view.
     */
    public void stopRefresh() {
        if (mPullRefreshing == true) {
            mPullRefreshing = false;
            resetHeaderHeight();
        }
    }

    /**
     * stop load more, reset footer view.
     */
    public void stopLoadMore() {
        if (mPullLoading == true) {
            mPullLoading = false;
            mFooterView.setState(XListViewFooter.STATE_NORMAL);
        }
    }

    /**
     * set last refresh time
     *
     * @param time
     */
    public void setRefreshTime(String time) {
        if (mHeaderTimeTextView != null) {
            mHeaderTimeTextView.setVisibility(View.VISIBLE);
            mHeaderTimeView.setText(time);
        }
    }

    private void invokeOnScrolling() {
        if (mScrollListener instanceof OnXScrollListener) {
            OnXScrollListener l = (OnXScrollListener) mScrollListener;
            l.onXScrolling(this);
        }
    }

    private void updateHeaderHeight(float delta) {
        mHeaderView.setVisiableHeight((int) delta);
        // mHeaderView.setVisiableHeight((int) delta
        // + mHeaderView.getVisiableHeight());
        if (mEnablePullRefresh && !mPullRefreshing) { // 未处于刷新状态，更新箭头
            if (mHeaderView.getVisiableHeight() > mHeaderViewHeight) {
                mHeaderView.setState(XListViewHeader.STATE_READY);
            } else {
                mHeaderView.setState(XListViewHeader.STATE_NORMAL);
            }
        }
        setSelection(0); // scroll to top each time
    }

    /**
     * 开启下拉更新
     */
    public void startRefresh() {
        mHeaderViewHeight = (int) getResources().getDimension(
                R.dimen.xlistview_header_height);
        updateHeaderHeight(mHeaderViewHeight);
        invokeOnScrolling();
        mScroller
                .startScroll(0, 0, 0, mHeaderViewHeight, SCROLL_DURATION + 200);
        // if (getFirstVisiblePosition() == 0) {
        if (mEnablePullRefresh) {
            mPullRefreshing = true;
            mHeaderView.setState(XListViewHeader.STATE_REFRESHING);
            System.out.println("mListViewListener:" + mListViewListener);
            if (mListViewListener != null) {
                mListViewListener.onRefresh();
            }
        }
        resetHeaderHeight();
        // }
    }

    /**
     * reset header view's height.
     */
    private void resetHeaderHeight() {
        int height = mHeaderView.getVisiableHeight();
        if (height == 0) // not visible.
            return;
        // refreshing and header isn't shown fully. do nothing.
        if (mPullRefreshing && height <= mHeaderViewHeight) {
            return;
        }
        int finalHeight = 0; // default: scroll back to dismiss header.
        // is refreshing, just scroll back to show all the header.
        if (mPullRefreshing && height > mHeaderViewHeight) {
            finalHeight = mHeaderViewHeight;
        }
        mScrollBack = SCROLLBACK_HEADER;
        mScroller.startScroll(0, height, 0, finalHeight - height,
                SCROLL_DURATION);
        // trigger computeScroll
        invalidate();
    }

    private void updateFooterHeight(float delta) {
        // int height = mFooterView.getBottomMargin() + (int) delta;
        if (mEnablePullLoad && !mPullLoading) {
            if (delta > PULL_LOAD_MORE_DELTA) { // height enough to invoke load
                // more.
                mFooterView.setState(XListViewFooter.STATE_READY);
            } else {
                mFooterView.setState(XListViewFooter.STATE_NORMAL);
            }
        }
        // mFooterView.setBottomMargin(height);
        mFooterView.setBottomMargin((int) delta);

        // setSelection(mTotalItemCount - 1); // scroll to bottom
    }

    private void resetFooterHeight() {
        int bottomMargin = mFooterView.getBottomMargin();
        if (bottomMargin > 0) {
            mScrollBack = SCROLLBACK_FOOTER;
            mScroller.startScroll(0, bottomMargin, 0, -bottomMargin,
                    SCROLL_DURATION);
            invalidate();
        }
    }

    private void startLoadMore() {
        mPullLoading = true;
        mFooterView.setState(XListViewFooter.STATE_LOADING);
        if (mListViewListener != null) {
            mListViewListener.onLoadMore();
        }
    }

    private int mHeaderViewVisiableHeight = 0;
    private int mFooterBottomMargin = 0;
    private float mDeltaY = 0;

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        if (mLastY == -1) {
            mLastY = ev.getRawY();
        }
        if (!isPullMore) {
            return super.onTouchEvent(ev);
        }
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:// 按下去
                mLastY = ev.getRawY();
                mDeltaY = 0;
                mHeaderViewVisiableHeight = mHeaderView.getVisiableHeight();
                mFooterBottomMargin = mFooterView.getBottomMargin();
                break;
            case MotionEvent.ACTION_MOVE: // 移动

                mDeltaY = ev.getRawY() - mLastY;
                if (getFirstVisiblePosition() == 0
                        && (mHeaderView.getVisiableHeight() > 0 || mDeltaY > 0)) {
                    // 下拉
                    // the first item is showing, header has shown or pull down.
                    updateHeaderHeight(mHeaderViewVisiableHeight + mDeltaY
                            / OFFSET_RADIO);
                    invokeOnScrolling();
                } else if (getLastVisiblePosition() == mTotalItemCount - 1
                        && (mFooterView.getBottomMargin() > 0 || mDeltaY < 0)) {
                    // last item, already pulled up or want to pull up.
                    // 上拉
                    if (mEnablePullLoad)
                        updateFooterHeight(mFooterBottomMargin - mDeltaY
                                / OFFSET_RADIO);
                }
                break;
            default: // 放开
                mLastY = -1; // reset
                if (getFirstVisiblePosition() == 0 && mDeltaY > 0) {
                    // invoke refresh
                    if (mEnablePullRefresh
                            && mHeaderView.getVisiableHeight() > mHeaderViewHeight) {
                        mHeaderView.setState(XListViewHeader.STATE_REFRESHING);
                        if (mListViewListener != null && !mPullRefreshing) {
                            mPullRefreshing = true;
                            mListViewListener.onRefresh();
                        }
                    }
                    resetHeaderHeight();
                } else if (getLastVisiblePosition() == mTotalItemCount - 1
                        && mDeltaY < 0) {
                    // invoke load more.
                    if (!mPullLoading && mEnablePullLoad
                            && mFooterView.getBottomMargin() > PULL_LOAD_MORE_DELTA) {
                        startLoadMore();
                    }
                    resetFooterHeight();
                }
                break;
        }
        return super.onTouchEvent(ev);
    }

    @Override
    public void computeScroll() {
        if (mScroller.computeScrollOffset()) {
            if (mScrollBack == SCROLLBACK_HEADER) {
                mHeaderView.setVisiableHeight(mScroller.getCurrY());
            } else {
                mFooterView.setBottomMargin(mScroller.getCurrY());
            }
            postInvalidate();
            invokeOnScrolling();
        }
        super.computeScroll();
    }

    @Override
    public void setOnScrollListener(OnScrollListener l) {
        mScrollListener = l;
    }

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {
        if (mScrollListener != null) {
            mScrollListener.onScrollStateChanged(view, scrollState);
        }
        if (getRollHiddenView() != null) {
            switch (scrollState) {
                case OnScrollListener.SCROLL_STATE_IDLE:// 空闲状态
                    new AsyncTask<Void, Void, Void>() {

                        @Override
                        protected void onPreExecute() {

                        }

                        @Override
                        protected Void doInBackground(Void... params) {
                            try {
                                Thread.sleep(2000);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            return null;
                        }

                        @Override
                        protected void onPostExecute(Void result) {
                            getRollHiddenView().setVisibility(VISIBLE);
                        }
                    }.execute();
                    break;
                case OnScrollListener.SCROLL_STATE_FLING:// 滚动状态
                    getRollHiddenView().setVisibility(GONE);
                    break;
                case OnScrollListener.SCROLL_STATE_TOUCH_SCROLL:// 触摸后滚动
                    getRollHiddenView().setVisibility(GONE);
                    break;
            }
        }
    }

    /**
     * firstVisibleItem 可以见的第一个item的位置 visibleItemCount 可见的个数 totalItemCount 总个数
     */
    @Override
    public void onScroll(AbsListView view, int firstVisibleItem,
                         int visibleItemCount, int totalItemCount) {
        // send to user's listener
        mTotalItemCount = totalItemCount;
        if (mScrollListener != null) {
            mScrollListener.onScroll(view, firstVisibleItem, visibleItemCount,
                    totalItemCount);
        }
        if (mRollBottonIsMoveHiddenView && mRollHiddenView != null) {
            if (firstVisibleItem > (totalItemCount - visibleItemCount - 1)
                    && visibleItemCount < totalItemCount) {
                FrameLayout frameLayout = (FrameLayout) mRollHiddenView
                        .getParent();
                frameLayout.setPadding(0, 0, 0, 160);
            } else {
                FrameLayout frameLayout = (FrameLayout) mRollHiddenView
                        .getParent();
                frameLayout.setPadding(0, 0, 0, 0);
            }
        }
    }

    public void setXListViewListener(IXListViewListener l) {
        mListViewListener = l;
    }

    /**
     * you can listen ListView.OnScrollListener or this one. it will invoke
     * onXScrolling when header/footer scroll back.
     */
    public interface OnXScrollListener extends OnScrollListener {
        public void onXScrolling(View view);
    }

    /**
     * implements this interface to get refresh/load more event.
     */
    public interface IXListViewListener {
        public void onRefresh();

        public void onLoadMore();
    }

    public View getRollHiddenView() {
        return mRollHiddenView;
    }

    public void setRollHiddenView(View mRollHiddenView) {
        this.mRollHiddenView = mRollHiddenView;
    }

    public boolean isRollBottonIsMoveHiddenView() {
        return mRollBottonIsMoveHiddenView;
    }

    public void setRollBottonIsMoveHiddenView(
            boolean mRollBottonIsMoveHiddenView) {
        this.mRollBottonIsMoveHiddenView = mRollBottonIsMoveHiddenView;
    }
}
